package com.cennavi.minemapdemo.activity.ue;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.geometry.LatLngBounds;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayer;
import com.minedata.minemap.overlay.MarkerLayerOptions;

import java.util.ArrayList;
import java.util.List;


public class CameraMoveActivty extends BaseActivty {

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private Context mContext;

    private TextView btnFly;
    private TextView btnEase;
    private TextView btnMove;
    private TextView btnFit;

    private List<LatLng> data;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);

        setContentView(R.layout.activity_ue_camera_move);

        mContext = this;
        mapView = findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        initData();
        initMap();
        initView();

    }

    private void initMap() {
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @SuppressLint("RtlHardcoded")
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(true);
                mineMap.getUiSettings().setLogoEnabled(true);
                mineMap.setStyleUrl(Config.mBaseUrl + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {
                        mineMap.setTrafficShow(false); //是否展示交通路况信息
                        addImageToMap();
                    }
                });

                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(32.03553118256124,118.7833267450))
                                .zoom(16)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别
                addFourPoints();
            }
        });

    }
    //加载可能的图片资源
    private void addImageToMap() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.icon_gcoding);
        mineMap.addImage(R.mipmap.icon_gcoding+"", bitmap);
    }


    private void initView() {

        btnFly = findViewById(R.id.btn_fly);
        btnEase = findViewById(R.id.btn_ease);
        btnMove = findViewById(R.id.btn_move);
        btnFit = findViewById(R.id.btn_fit);
		final ImageView zoomIn = findViewById(R.id.zoomin);
		final ImageView zoomOut = findViewById(R.id.zoomout);

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (view.equals(zoomIn)) {

                	zoomIn(view);
				} else if (view.equals(zoomOut)) {

                	zoomOut(view);
				} else if (view.equals(btnFly)) {

                    perfomCameraFly();
                } else if (view.equals(btnEase)) {

                    perfomCameraEase();
                } else if (view.equals(btnMove)){

                    perfomCameraMove();
                } else if (view.equals(btnFit)) {

                    perfomCameraFit();
                }
            }
        };

		zoomIn.setOnClickListener(listener);
		zoomOut.setOnClickListener(listener);
        btnFly.setOnClickListener(listener);
        btnEase.setOnClickListener(listener);
        btnMove.setOnClickListener(listener);
        btnFit.setOnClickListener(listener);

    }

    private int count = 0;
    /**
     * 处理视角的飞行移动模式
     * 建议相距较远的可以使用本功能
     */
    private void perfomCameraFly() {

        CameraPosition cameraPosition = new CameraPosition.Builder().target(data.get(count)).zoom(14)
                .build();
        if (mineMap != null) {
            mineMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 5000);
        }

        if (count < 3) count++;
        else count = 0;
    }

    /**
     * 处理视角的平移模式
     *
     * 距离较近平行移动的情况来进行。
     */
    private void perfomCameraEase() {
        mineMap.easeCamera(CameraUpdateFactory.newLatLng(data.get(count)), 1000);
        if (count < 3) count++;
        else count = 0;
    }

    /**
     * 处理视角的瞬移模式
     *
     * 距离较近平行移动的情况来进行。
     */
    private void perfomCameraMove() {
        mineMap.moveCamera(CameraUpdateFactory.newLatLng(data.get(count)));
        if (count < 3) count++;
        else count = 0;
    }


    /**
     * 处理视角的自适应模式
     */
    private void perfomCameraFit() {

        double right = Double.MAX_VALUE , left = Double.MIN_VALUE;
        double top = Double.MAX_VALUE , down = Double.MIN_VALUE;

        for (int i =0;i<data.size(); i++) {

            double x = data.get(i).getLongitude();
            double y = data.get(i).getLatitude();

            //线条在屏幕的自适应
            if (left < x) left = x;
            if (right > x) right = x;
            if (top > y) top = y;
            if (down < y) down = y;
        }

        LatLng left_top = new LatLng(top,left);
        LatLng right_down = new LatLng(down,right);
        LatLngBounds latLngBounds = new LatLngBounds.Builder()
                .include(left_top) // Northeast
                .include(right_down) // Southwest
                .build();

        mineMap.easeCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,200),5000);

    }

    public void zoomIn(View view) {
		if (mineMap != null) {
			mineMap.moveCamera(CameraUpdateFactory.zoomIn());
		}
	}

	public void zoomOut(View view) {
		if (mineMap != null) {
			mineMap.moveCamera(CameraUpdateFactory.zoomOut());
		}
	}


    /**
     * 给地图添加4个点
     */
    private void addFourPoints() {

        List<MarkerLayerOptions.MarkerItem> markerItemList = new ArrayList<>();
        for (int i=0; i<data.size();i++) {

            MarkerLayerOptions.MarkerItem markerItem = new MarkerLayerOptions.MarkerItem().position(data.get(i)).icon(R.mipmap.icon_gcoding+"");
            markerItemList.add(markerItem);
        }

        addGraphics(markerItemList);

    }

    private MarkerLayer stopsLayer;
    private void addGraphics(List<MarkerLayerOptions.MarkerItem> list) {

        if (stopsLayer == null || !stopsLayer.isLayerExist()){

            MarkerLayerOptions options = new MarkerLayerOptions("BusStops")
                    .textColor("#6495ED")
                    .textHaloColor("#6495ED")
                    .textHaloWidth(0.2f);

            options.textIgnorePlacement(false);
            options.textAllowOverlap(false);
            options.iconTextFit(MarkerLayerOptions.MARKER_ICON_TEXT_FIT_BOTH);  //文字与背景融合
            options.iconTextFitPadding(new Float[]{5f, 10f, 5f, 10f});  //融合 边界
            options.addAll(list);
            stopsLayer = mineMap.addLayer(options);
        }else {
            stopsLayer.clear();
            stopsLayer.addAll(list);
            stopsLayer.update();
        }
    }

    private void initData() {

        data = new ArrayList<>();
        data.add(new LatLng(39.916263,116.401969)); //北京
        data.add(new LatLng(34.388254,109.036726)); //西安
        data.add(new LatLng(26.657252,106.645078)); //贵阳
        data.add(new LatLng(32.01627, 118.87309));  //南京

    }


    //地图生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();
    }
}
